package com.oct.ywsc.job.schedule;

import com.oct.ywsc.core.config.ThreadConfig;
import com.oct.ywsc.job.TransTaskScheduler;
import com.oct.ywsc.job.MsgTransTask;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 消息转换执行器
 */
public class TransJobExecutor {

    private ThreadConfig threadConfig;

    private LinkedBlockingQueue transRuleQueue ;

    private ThreadPoolExecutor executor;

    public TransJobExecutor(ThreadConfig threadConfig) {
        this.threadConfig = threadConfig;
        transRuleQueue = new LinkedBlockingQueue<>(threadConfig.getQueueCapacity());
        executor = new ThreadPoolExecutor(threadConfig.getCorePoolSize(),threadConfig.getMaximumPoolSize(),
                threadConfig.getKeepAliveTime(), TimeUnit.MINUTES,transRuleQueue, new CustomerRejectedExecutionHandler());
    }


    /**
     * 添加转换任务
     * @param job
     */
    public void add(MsgTransTask job) {
        executor.execute(job);
    }

    /**
     * 获取转换任务数量
     * @return
     */
    public long jobSize() {

        return transRuleQueue.size();
    }


    /**
     * 判断是否可以接受任务
     * @param maxPollRecords 单次拉取消息数量
     * @return
     */
    public boolean canAcceptable(int maxPollRecords) {
        // 消息队列中消息容量未达到最大容量则可接收任务
        boolean canAcceptable = this.transRuleQueue.size() < this.threadConfig.getQueueCapacity()-maxPollRecords;

        TransTaskScheduler.canAcceptable = canAcceptable;
        return canAcceptable;
    }





}
